package org.example.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;

import net.sf.jsqlparser.expression.StringValue;
import org.example.order.VO.UserVO;
import org.example.order.VO.LoginVO;
import org.example.order.VO.RegisterVO;
import org.example.order.entity.User;
import org.example.order.mapper.UserMapper;
import org.example.order.service.UserService;
import org.example.order.util.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public void add(User user) {
        baseMapper.insert(user);
    }

    @Override
    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            baseMapper.deleteById(id);
        }
    }

    @Override
    public void update(User user) {
        baseMapper.updateById(user);
    }

    @Override
    public User selectById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<User> selectAll() {
        return baseMapper.selectList(null);
    }

    @Override
    public PageInfo<User> selectPage(User user,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        // 使用 QueryWrapper 构建查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        // 如果 user 不为 null，添加条件
        if (user != null) {
            // 模糊查询标题
            if (StringUtils.isNotBlank(user.getUsername())) {
                wrapper.like("username", user.getUsername());
            }
        }
        List<User> list = baseMapper.selectList(wrapper);
        return new PageInfo<>(list);
    }

    @Override
    public boolean saveBatch(Collection<User> entityList) {
        return super.saveBatch(entityList);
    }
    public User getByUserName(String Username){
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,Username);
        return this.getOne(wrapper);
    }
    public User getByPhone(String phone){
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        return this.getOne(wrapper);
    }
    public List<User> getUserList(String keyword) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        if (org.springframework.util.StringUtils.hasText(keyword)) {
            wrapper.like(User::getUsername, keyword)
                    .or()
                    .like(User::getPhone, keyword);
        }

        wrapper.orderByDesc(User::getCreateTime);

        // 返回 List 而不是 IPage
        return this.list(wrapper);
    }

        @Transactional(rollbackFor = Exception.class)
        public User register(RegisterVO registerVO){
            User existUser=this.getByUserName(registerVO.getUsername());
            if(existUser!=null){
                throw new RuntimeException("用户名已存在");
            }
            if (org.springframework.util.StringUtils.hasText(registerVO.getPhone())) {
                existUser = this.getByPhone(registerVO.getPhone());
                if (existUser != null) {
                    throw new RuntimeException("手机号已被注册");
                }
            }
            User user=new User();
            user.setUsername(registerVO.getUsername());
            user.setNickname(registerVO.getNickname() != null ? registerVO.getNickname() : registerVO.getUsername());
            user.setPassword(passwordEncoder.encode(registerVO.getPassword()));
            user.setPhone(registerVO.getPhone());
            user.setStatus(1);
            user.setGender(0);
            this.save(user);
            return user;
        }
        @Transactional(rollbackFor = Exception.class)
        public UserVO login(LoginVO loginVO,String ip) {
            User user=null;
            if(org.springframework.util.StringUtils.hasText(loginVO.getIdentifier())){
                user=this.getByUserName(loginVO.getIdentifier());
            }
            if(org.springframework.util.StringUtils.hasText(loginVO.getIdentifier())&&user==null){
                user=this.getByPhone(loginVO.getIdentifier());
            }
            if(user==null){
                throw new RuntimeException("用户不存在");
            }
            if(!passwordEncoder.matches(loginVO.getPassword(),user.getPassword())){
                throw new RuntimeException("用户密码错误");
            }
            if(user.getStatus()==0){
                throw new RuntimeException("账号已被禁用");
            }
            Map<String, String> payload = new HashMap<>();
            payload.put("id",user.getId().toString());
            payload.put("level","1");
            String token= JWTUtils.getToken(payload);
            userMapper.updateLoginInfo(user.getId(), LocalDateTime.now(),ip);
            UserVO userVO=new UserVO();
            BeanUtils.copyProperties(user,userVO);
            userVO.setToken(token);
            return userVO;

        }

        public UserVO getUserInfoByToken(String token) {
            if(!org.springframework.util.StringUtils.hasText(token)){
                return null;
            }
            LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(User::getToken,token);
            User user=this.getOne(wrapper);
            if(user==null){
                return null;
            }
            UserVO userVO=new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return userVO;
        }

    public String updateUserInfo(UserVO userVO) {
        if (userVO.getId() == null || userVO.getId() == 0) {
            return "没有传递id";
        }
        User existingUser = this.getById(userVO.getId());
        if (existingUser == null) {
            return "用户不存在";
        }

        User userToUpdate = new User();
        userToUpdate.setId(userVO.getId());

        // 只更新非默认值字段
        if (isNotBlank(userVO.getUsername())) userToUpdate.setUsername(userVO.getUsername());
        if (isNotBlank(userVO.getNickname())) userToUpdate.setNickname(userVO.getNickname());
        if (isNotBlank(userVO.getPhone())) userToUpdate.setPhone(userVO.getPhone());
        if (isNotBlank(userVO.getAvatar())) userToUpdate.setAvatar(userVO.getAvatar());
        if (userVO.getGender() != null ) userToUpdate.setGender(userVO.getGender());
        if (userVO.getBirthday() != null && !userVO.getBirthday().toString().isEmpty()) userToUpdate.setBirthday(userVO.getBirthday());
        if (userVO.getStatus() != null ) userToUpdate.setStatus(userVO.getStatus());
        if (userVO.getLastLoginTime() != null && !userVO.getLastLoginTime().toString().isEmpty()) userToUpdate.setLastLoginTime(userVO.getLastLoginTime());
        if (isNotBlank(userVO.getLastLoginIp())) userToUpdate.setLastLoginIp(userVO.getLastLoginIp());
        if (userVO.getIsDeleted() != null && userVO.getIsDeleted() != 0) userToUpdate.setIsDelete(userVO.getIsDeleted());
        if (isNotBlank(userVO.getToken())) userToUpdate.setToken(userVO.getToken());
        if (isNotBlank(userVO.getDescription())) userToUpdate.setDescription(userVO.getDescription());

        boolean updated = this.updateById(userToUpdate);
        return updated ? "修改成功" : "修改失败";
    }
    private boolean isNotBlank(String str) {
        return str != null && !str.trim().isEmpty();
    }

        public boolean updatePassword(Long userId, String oldPassword, String newPassword) {
            User user=this.getById(userId);
            if(user ==null){
                throw new RuntimeException("用户不存在");
            }
            if(!passwordEncoder.matches(oldPassword,user.getPassword())){
                throw new RuntimeException("原密码错误");
            }
            user.setPassword(passwordEncoder.encode(newPassword));
            return this.updateById(user);
        }

        public boolean updateStatus(Long userId, Integer status) {
            User user = new User();
            user.setId(userId);
            user.setStatus(status);
            return this.updateById(user);
        }

    @Transactional(rollbackFor = Exception.class)
    public boolean removeUser(Long userId) {
        // MyBatis Plus 的 removeById 会自动处理逻辑删除
        return this.removeById(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean removeUserBatch(List<Long> userIds) {
        // MyBatis Plus 的 removeByIds 会自动处理逻辑删除
        return this.removeByIds(userIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean restoreUser(Long userId) {
        // 手动将 isDeleted 字段设置为 0，恢复用户
        return userMapper.restoreUser(userId)>0;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean restoreUserBatch(List<Long> userIds) {
        // 批量恢复用户
        return userMapper.restoreUserBatch(userIds)>0;
    }

}
